import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.System.out;

public class Book {
    static final Pattern prettyName = Pattern.compile("^([^(]+)\\([^)]+\\) *$");

    public String ArticleName;
    public String Title;
    public String OriginalTitle;
    public String Author;

    public String getPrettyArticleName(){
        Matcher matcher = prettyName.matcher(ArticleName);
        if (matcher.matches())
        {
            return matcher.group(1);
        }
        return ArticleName;
    }

    public static List<Book> load(String path) throws JDOMException, IOException {
        ArrayList<Book> books = new ArrayList<Book>();

        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File(path);

        Document document = builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("Book");

        for (int i=0; i< list.size(); i++)
        {
            Element node = (Element) list.get(i);

            Book book = new Book();
            book.ArticleName = node.getChildText("ArticleName");
            book.Author = node.getChildText("Author");
            book.OriginalTitle = node.getChildText("OriginalTitle");
            book.Title = node.getChildText("Title");

            books.add(book);
        }

        return books;
    }
}
